package com.mxchen.lottery.domain.strategy.service.algorithm.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.mxchen.lottery.domain.strategy.model.AwardRateInfo;
import com.mxchen.lottery.domain.strategy.service.algorithm.BaseAlgorithm;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : hmxchen
 * @program : lottery-964-mxchen
 * @description :
 * 必中奖策略抽奖，排掉已经中奖的概率，重新计算中奖范围
 * @create : 2021-12-16 09:36
 **/
@Component("defaultRateRandomDrawAlgorithm")
public class DefaultRateRandomDrawAlgorithm extends BaseAlgorithm {
    /**
     * SecureRandom 生成随机数，索引到对应的奖品信息返回结果
     *
     * @param strategyId 策略ID
     * @param excludeAwardIds 排除掉已经不能作为抽奖的奖品ID，留给风控和空库存使用
     * @return 中奖结果
     */
    @Override
    public String randomDraw(Long strategyId, List<String> excludeAwardIds) {
        // 排除掉不在抽奖范围的奖品ID集合
        List<AwardRateInfo> rateInfos = awardRateInfoMap.get(strategyId).stream()
                .filter(u -> !excludeAwardIds.contains(u.getAwardId()))
                .collect(Collectors.toList());
        if(rateInfos.size() <= 1){
            return rateInfos.size()==0?"":rateInfos.get(0).getAwardId();
        }
        //获取随机数
        int randomVal = super.getRandom();
        //获取抽奖范围内的总概率
        BigDecimal differenceDenominator = rateInfos.stream()
                .map(AwardRateInfo::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        int cursorVal = 0;
        for(AwardRateInfo awardRateInfo:rateInfos){
            //计算当前概率与总的之比
            int rateVal = awardRateInfo.getAwardRate().divide(differenceDenominator, 2, BigDecimal.ROUND_UP)
                    .multiply(new BigDecimal(100)).intValue();
            if (randomVal <= (cursorVal + rateVal)) {
                return awardRateInfo.getAwardId();
            }
            cursorVal += rateVal;
        }
        return "";
    }
}
